import React, {FC, useCallback, useContext, useEffect, useState} from 'react';
import "./HxFlexibleArticleGrid.less";
import EsSearchFilters from "@/pages/SearchPage/common/EsSearchFilters";
import EsSearchFilterPart from "@/pages/SearchPage/common/EsSearchFilters/EsSearchFilterPart";
import {FormattedMessage, useLocation} from "@@/exports";
import {AppstoreOutlined, BookOutlined, CaretDownOutlined, FieldTimeOutlined, FolderOutlined} from "@ant-design/icons";
import {Button, Checkbox, Popover, Space, Spin} from "antd";
import HxFlexibleDataGrid, {HxFlexibleDataGridViewMode} from "@/components/HxFlexibleDataGrid";
import HxIcon from "@/components/HxIcon";
import {correspVal} from "@/utils/biz";
import {HxArticleNormalItem} from "@/components/HxArticleItem";
import HxPagination from "@/components/HxPagination";
import * as API from "@/services";
import useJournalArticleHelp from "@/pages/JournalPage/JournalDetail/commons/useJournalArticleHelp";
import JournalArticleShare from "@/pages/JournalPage/JournalDetail/commons/JournalArticleShare";
import JournalArticleQuote from "@/pages/JournalPage/JournalDetail/commons/JournalArticleQuote";
import { KfModal, useBackendEnum } from 'kf-web-library';
import {FrontArticle} from "@/services";
import usePgSearch, {getLastQueryValue} from "@/pages/SearchPage/common/usePgSearch";
import {HxConfigContext} from "@/layouts/HxConfigContext";
import {useLocalStorageState, useRequest} from "ahooks";
import lodash from "lodash";


const ArticleTableActions = ({article, mutate}: { article: API.FrontArticle, mutate: (art: API.FrontArticle) => void }) => {
  const {downloadArticlePdf, downloadArticlePdfIcon, downloading, favArticle, favIcon, doiUrl} = useJournalArticleHelp(article);
  return (
    <Space size={8}>
      <a onClick={(e) => {
        e.preventDefault();
        downloadArticlePdf();
      }}>
        {downloadArticlePdfIcon}
      </a>
      <a onClick={(e) => {
        e.preventDefault();
        favArticle((art) => {
          mutate(art);
        });
      }}>
        {favIcon}
      </a>
      <Popover trigger={"click"} content={
        <JournalArticleShare article={article}/>
      }>
        <a><HxIcon type={"hxicon-code"}/></a>
      </Popover>
      <Popover trigger={"click"}
               content={(
                 <JournalArticleQuote article={article}/>
               )}>
        <a><HxIcon type={"hxicon-yinyong"}/></a>
      </Popover>
    </Space>
  );
};

export interface HxFlexibleArticleGridProps {
  specType?: "guide" | "consensus";
  searchRecordListTopExtra?: React.ReactNode;
  additionalQuery?: Record<string, any>;
  showEggs?: boolean;
}

const HxFlexibleArticleGrid: FC<HxFlexibleArticleGridProps> = (props) => {
  const location = useLocation();
  const {specType, showEggs = false, searchRecordListTopExtra, additionalQuery} = props;
  const {enumDict, enumTypeDict, getBackendEnum} = useBackendEnum();
  const [selectedRecords, setSelectedRecords] = useState<FrontArticle[]>([])
  const [viewMode, setViewMode] = useState<HxFlexibleDataGridViewMode>("list")
  const [esOrderType, setEsOrderType] = useState("RELEVANCE")
  const [selectAll, setSelectAll] = useState<boolean | "clear" | undefined>()
  const {currentSearch} = usePgSearch();
  const {isZhCN} = useContext(HxConfigContext);
  const [exportOpen, setExportOpen] = useState(false);

  //检索历史
  const [historySearchs, setHistorySearchs] = useLocalStorageState<string[]>(
    '_history_searchs_',
    {
      defaultValue: [],
    },
  );
  const displayHistorySearch = historySearchs || [];

  const dataReq = useRequest((p) => {
    let translatedQuery = {};
    if (specType) {
      if (specType === "guide") {
        translatedQuery = {
          specialTopicIds: "5",
        }
      } else if (specType === "consensus") {
        translatedQuery = {
          specialTopicIds: "1",
        }
      }
    }
    const searchText = getLastQueryValue(currentSearch, "dsl") || getLastQueryValue(currentSearch, "searchText");

    if (!!searchText) {
      const newHistorySearchs: string[] = [searchText, ...displayHistorySearch];
      if (newHistorySearchs.length > 10) {
        newHistorySearchs.pop();
      }
      setHistorySearchs(newHistorySearchs);
    }

    return API.queryFrontArticlesByEs({
      ...p,
      ...lodash.omit(currentSearch, ["dsl", "searchText"]),
      esOrderType,
      searchText,
      ...translatedQuery,
      ...additionalQuery
    });
  }, {
    onSuccess: (data) => {
      setSelectAll(undefined);
    },
    refreshDeps: [currentSearch, esOrderType, additionalQuery],
  });

  const mutate = useCallback((article: API.FrontArticle) => {
    dataReq?.mutate((oldData) => {
      return {
        ...oldData,
        data: oldData!.data.map((item) => {
          if (item.id === article.id) {
            return {
              ...article,
            }
          }
          return item;
        })
      } as API.RespPageResult<API.FrontArticle>;
    })
  }, []);

  const records = dataReq.data?.data || [];
  const aggs = dataReq.data?.extras?.aggs;

  const existAnyAgg = showEggs ? (!!aggs && !!Object.values(aggs).find((t: any) => t.length > 0)) : false;

  useEffect(() => {
    if (selectAll === "clear") {
      setSelectedRecords([]);
    } else if (typeof selectAll === 'boolean') {
      if (selectAll) {
        const selectedRecordIds = selectedRecords.map(t => t.id);
        setSelectedRecords([...selectedRecords, ...records.filter(t => !selectedRecordIds.includes(t.id))])
      } else {
        const recordIds = records.map(t => t.id);
        setSelectedRecords(selectedRecords.filter(t => !recordIds.includes(t.id)));
      }
    }
  }, [selectAll]);


  const exportQuotesAsTxt = useCallback(() => {
    // 获取 export-quotes 容器内的所有引文内容
    const exportContainer = document.querySelector('.export-quotes');
    if (!exportContainer) return;

    // 提取每个引文项的文本内容
    const quoteItems = exportContainer.querySelectorAll('.export-quote-item');
    const textContent = Array.from(quoteItems).map(item => {
      // 获取序号和引文内容
      const seqElement = item.querySelector('.export-quote-item-seq');
      const seqText = seqElement ? seqElement.textContent : '';

      // 获取引文主体内容（去除复制按钮等操作元素）
      const quoteElement = item.querySelector('.ant-typography')
      const quoteContent = quoteElement ? quoteElement.textContent?.replace(/\s+/g, ' ').trim() : '';
      return `${seqText} ${quoteContent}`;
    }).join('\n'); // 每个引文之间用两个换行分隔

    // 创建并下载文本文件
    const blob = new Blob([textContent], { type: 'text/plain;charset=utf-8' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = '引文.txt';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
  }, []);

  return (
    <div className={"hx-flexible-article-grid-container search-result-page-content"}>
      {
        !!existAnyAgg && (
          <div className={"search-record-filters"}>
            <EsSearchFilters>
              <EsSearchFilterPart fieldName={"articleTypes"}
                                  title={<FormattedMessage id="search.article.filter.articleTypes"/>}
                                  icon={<FolderOutlined/>}
                                  options={aggs?.typeAggs || []}/>
              <EsSearchFilterPart fieldName={"adviseTypes"}
                                  title={<FormattedMessage id="search.article.filter.adviseTypes"/>}
                                  icon={<AppstoreOutlined/>}
                                  options={(aggs?.adviseTypeAggs || []).map((agg: any) => {
                                    return {...agg, displayName: getBackendEnum("ArticleAdviseType", agg.key)?.i18EnumDesc}
                                  })}
              />
              <EsSearchFilterPart fieldName={"journalNameCns"}
                                  title={<FormattedMessage id="search.article.filter.journalNames"/>}
                                  icon={<BookOutlined/>}
                                  options={aggs?.journalCnAggs || []}/>
              <EsSearchFilterPart fieldName={"publicationYears"}
                                  title={<FormattedMessage id="search.article.filter.publicationYears"/>}
                                  icon={<FieldTimeOutlined/>}
                                  options={aggs?.publishedYearAggs || []}/>
            </EsSearchFilters>
          </div>
        )
      }

      <div className={"search-record-list"}>
        {!!aggs && searchRecordListTopExtra}
        <Spin spinning={dataReq.loading}>
          <HxFlexibleDataGrid
            header={(
              <div className={"search-record-tools-wrapper"}>
                <div className={"search-record-tools-left"}>
                  <div className={"search-record-row-select"}>
                    <Checkbox checked={typeof selectAll === 'boolean' ? selectAll : false} onChange={(e) => {
                      e.preventDefault();
                      setSelectAll(e.target.checked)
                    }}>全选</Checkbox>
                    <span className={"search-record-row-select-count"}>
                          已选<span>{selectedRecords.length}</span>
                        </span>
                    <a className={"search-record-row-select-clear"} onClick={(e) => {
                      e.preventDefault();
                      setSelectAll("clear")
                    }}>清除</a>
                  </div>
                  <div className={"search-record-export-download"}>
                    <Button size={"small"} disabled={!selectedRecords.length} onClick={()=>setExportOpen(true)}>批量导出</Button>
                  </div>
                </div>
                <div className={"search-record-tools-right"}>
                  <div className={"search-record-order-by"}>
                    <span>排序:</span>
                    <div className={"search-record-order-item"}>
                      <a onClick={() => setEsOrderType("RELEVANCE")} className={esOrderType === "RELEVANCE" ? "active" : ""}>
                        相关度{esOrderType === "RELEVANCE" && <CaretDownOutlined/>}
                      </a>
                      <a onClick={() => setEsOrderType("DATE")} className={esOrderType === "DATE" ? "active" : ""}>
                        发表时间{esOrderType === "DATE" && <CaretDownOutlined/>}
                      </a>
                    </div>
                  </div>
                  <div className={"search-record-view-by"}>
                    <Button title={"切换为列表模式"} type={viewMode === "list" ? "primary" : "default"} icon={<HxIcon type={"hxicon-liebiao"}/>}
                            onClick={() => setViewMode("list")}/>
                    <Button title={"切换为表格模式"} type={viewMode === "table" ? "primary" : "default"}
                            icon={<HxIcon type={"hxicon-biaodanzujian-biaoge"}/>}
                            onClick={() => setViewMode("table")}/>
                  </div>
                </div>
              </div>
            )}
            selectedRecords={selectedRecords}
            onSelectedRecordsChange={setSelectedRecords}
            dataSource={records}
            viewMode={viewMode}
            rowKey={"id"}
            tableProps={{
              size: "small",
              columns: [
                {
                  title: "标题",
                  dataIndex: "articleTitleCn",
                  render: (_, record) => {
                    return correspVal(isZhCN, record?.articleTitleCn, record?.articleTitleEn)
                  }
                },
                {
                  title: "作者",
                  dataIndex: "articleAuthorCn",
                  render: (_, record) => {
                    return correspVal(isZhCN, record?.articleAuthorCn, record?.articleAuthorEn)
                  }
                },
                {
                  title: "所属期刊",
                  dataIndex: "journal",
                  width: 100,
                  render: (_, record) => {
                    return correspVal(isZhCN, record?.journal?.journalNameCn || record?.journalNameCn, record?.journal?.journalNameEn || record?.journalNameEn)
                  }
                },
                {
                  title: <FormattedMessage id="text.action"/>,
                  key: 'action',
                  align: "center",
                  width: 70,
                  render: (_, record) => {
                    return (
                      <ArticleTableActions article={record} mutate={mutate}/>
                    )
                  },
                },
              ]
            }}
            renderItem={(item, index) => {
              return (
                <HxArticleNormalItem
                  key={item.id}
                  selected={selectedRecords.findIndex((record) => record.id === item.id) != -1}
                  onSelectChange={(selected) => {
                    const newSelectedRecords = selected
                      ? [...selectedRecords, item]
                      : selectedRecords.filter((target) => target.id !== item.id);
                    setSelectedRecords(newSelectedRecords);
                  }}
                  showCover={true}
                  toolbarOnlyIcon={true}
                  article={item}
                  target={"_blank"}
                  onArticleChange={(art) => {
                    mutate(art);
                  }}/>
              )
            }}
          />
          {
            dataReq.data && (
              <div className={"hx-pagination-wrapper"}>
                <HxPagination size="default"
                              total={dataReq.data?.total}
                              current={dataReq.data.current}
                              pageSize={dataReq.data.pageSize}
                              onChange={(pageNum, pageSize) => {
                                dataReq.run({
                                  page: pageNum,
                                  pageSize
                                })
                              }}
                />
              </div>
            )
          }
        </Spin>
      </div>

      {
        (exportOpen && selectedRecords?.length) && (
          <KfModal
            title={(
              <div>
                格式引文
                <a href={"#"} className={"export-quotes-downbtn"} onClick={exportQuotesAsTxt}>
                  下载
                </a>
              </div>
            )}
            open={true}
            onCancel={() => {
              setExportOpen(false);
            }}
            footer={null}
            width={"80%"}
            destroyOnClose={true}
          >
            <div className={"export-quotes"}>
              {
                selectedRecords.map((t,tindex)=>{
                  return  (
                    <div className={"export-quote-item"}>
                      <div className={"export-quote-item-seq"}>[{tindex+1}]</div>
                      <JournalArticleQuote key={t.id} article={t} copyable={false} showTitle={false}/>
                    </div>
                  )
                })
              }
            </div>
          </KfModal>
        )
      }

    </div>
  );
};

export default HxFlexibleArticleGrid;
